package com.boot.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.boot.realm.MyRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(manager);
        Map<String,String> map = new HashMap<>();

        //配置权限拦截 在ini配置文件中[urls]部分
        // /main:url authc:需要授权才能访问
        // anon:匿名可以访问
        // perms[manage,buyer,seller]:需要有manage、buyer或者seller权限才能访问
        // roles[admin,buyer,guest]:需要有admin、buyer或者guest角色才能访问

        map.put("/main","authc");//只需要登录即可访问
        map.put("/manage","perms[manage]");//也是需要登录并且需要有对应的权限才能访问的
        map.put("/administrator","roles[administrator]");//需要登录并且需要有对应的权限才能访问
        factoryBean.setFilterChainDefinitionMap(map);

        //设置登录页面
        factoryBean.setLoginUrl("/login");
        //未授权页面
        factoryBean.setUnauthorizedUrl("/unauth");
        return factoryBean;
    }

    //DefaultWebSecurityManager:SecurityManager 管理主题(用户的)
    @Bean
    public DefaultWebSecurityManager manager(@Qualifier("myRealm") MyRealm myRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm);
        return manager;
    }

    //使用Spring创建bean
    @Bean
    public MyRealm myRealm(){
        return new MyRealm();
    }

    //thymeleaf的shiro标签
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}
